package cn.apotato.modules.mybatis.plus.config;

import cn.apotato.common.core.utils.SpringUtils;
import cn.apotato.modules.mybatis.plus.plungs.MyTenantLineHandler;
import cn.apotato.modules.mybatis.plus.plungs.TenantIdHandler;
import cn.apotato.modules.mybatis.plus.model.TenantInfo;
import cn.apotato.modules.mybatis.plus.properties.MPProperties;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.lang.Nullable;

import javax.annotation.Resource;

/**
 * mybatis +配置
 *
 * @author 胡晓鹏
 * @date 2023/05/18
 */
@EnableConfigurationProperties({DataSourceProperties.class, MPProperties.class})
@Configuration
public class MybatisPlusConfig {

    @Resource
    private MPProperties mpProperties;

    @Resource
    private TenantIdHandler tenantIdHandler;

    /**
     * 序列化枚举值为前端返回值
     * @return {@link Jackson2ObjectMapperBuilderCustomizer}
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer(){
        return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    }

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 多租户插件
        TenantInfo tenant = mpProperties.getTenant();
        if (tenant != null && tenant.isEnable()) {
            if (tenantIdHandler != null) {
                // 设置租户id, 这里说明，获取租户id的优先级为 TenantHandler > 配置文件
                tenant.setTenantIdFunction(tenantIdHandler.getTenantId());
                tenant.setTenantIdColumn(tenantIdHandler.getTenantIdColumn());
            }
            mpProperties.setTenant(tenant);
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new MyTenantLineHandler(mpProperties.getTenant())));
        }
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }
}
